//
//  TLUserAccount.swift
//  TLSinaWeiBo
//
//  Created by 谭亮 on 16/5/20.
//  Copyright © 2016年 tanliang. All rights reserved.
//

import UIKit

// 对象归档和解档
// 1.对象遵守NSCoding协议:知道对象要保存和解档哪些属性
// 2.调用归档和解档的方法

/// 用户账号
class TLUserAccount: NSObject,NSCoding {

    /// 用户授权的唯一票据
    var access_token: String?
    
    /// access_token的生命周期,单位是秒数,基本数据类型不能使用?.KVC会找不到
    var expires_in: NSTimeInterval = 0 {
        didSet {
            // KVC给expires_in属性赋值完后,来创建expiresDate
            expiresDate = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    
    /// 过期时间,方便比较时间
    var expiresDate: NSDate?
    
    /// 授权用户的UID
    var uid: String?
    
    /// 通过字典来创建模型
    init(dict: [String: AnyObject]) {
        super.init()
        
        // 对象创建好后才能使用对象的方法,内部会调用setValue(value: AnyObject?, forKey key:String),每次会拿一个Key和value调用一次
        //["access_token":"2.00VIgITG0HhZB5bd5ed79708qhZcaB","expires_in":157679999,"uid":5927379335]
        setValuesForKeysWithDictionary(dict)
        // setValuesForKeysWithDictionary 最终调用setValue:forKey: 调用几次看字典中有几个Key
        //setValue("2.00VIgITG0HhZB5bd5ed79708qhZcaB", forKey: "access_token")
        //setValue("157679999", forKey: "expires_in")
        //setValue("5927379335", forKey: "uid")
        //setValue("157679999", forKey: "remind_in")
    }
    
    
    // 当setValue:forKey:找不到key时会调用setValue:forUndefinedKey:,如果不是想setValue:forUndefinedKey:就会报错
    
    override func setValue(value: AnyObject?, forKey key: String) {
        super.setValue(value, forKey: key)
        //TLPrint(items: "\(key) :\(value)")
    }
    
    // setValue:forKey:在模型中找不到对应的属性走这个方法
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        TLPrint(items: "forUndefinedKey: \(key)")
    }
    
    // 打印方法 desciption
    override var description: String {
        get {
            return "用户账户:access_token: \(access_token),expires_in: \(expires_in),uid: \(uid),expiresDate: \(expiresDate)"
        }
    }
    
    // MARK: - 归档和解档
    /// 解档
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expires_in = aDecoder.decodeDoubleForKey("expires_in")
        uid = aDecoder.decodeObjectForKey("uid") as? String
        expiresDate = aDecoder.decodeObjectForKey("expiresDate") as? NSDate
    }
    
    /// 归档
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token,forKey:"access_token")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(expiresDate, forKey: "expiresDate")
    }
}
